#include "usermodel.h"
#include "database/dbtabuser.h"

UserModel::UserModel(int colCnt,const QString& showName,QObject* parent):QAbstractListModel(parent),mColumnCount(colCnt)
  ,mDataCount(0),mColumnName(showName)
{
    mQuery = new DataBaseQuery();
    mTabName = DBTabUser::TAB_NAME;
}

UserModel::~UserModel()
{
    delete mQuery;
}


bool UserModel::submit()
{
    beginResetModel();
    QStringList keyList;
    keyList<<mColumnName<<DBTabUser::_USER_CODE<<DBTabUser::_PERMISSION<<DBTabUser::_PASSWD;
    mQuery->selectTable(mTabName,&keyList);
    endResetModel();
    mDataCount = mQuery->size();
    return true;
}

bool UserModel::submitFilter(const QString &str)
{
    beginResetModel();
    mQuery->exec("select DISTINCT "+mColumnName + " from " + mTabName
                     + " where " + QString(DBTabUser::_USER_NAME) + " LIKE \""+ str +"%\"");
    endResetModel();
    mDataCount = mQuery->size();
    return true;
}

int UserModel::rowCount(const QModelIndex &parent) const
{
    return (mDataCount+mColumnCount-1)/mColumnCount;
}

int UserModel::columnCount(const QModelIndex &parent) const
{
    return mColumnCount;
}

QVariant UserModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
    {
        return QVariant();
    }
//    if(role==ROLE_NAME)
//    {
//        if(mQuery->seek(index.row()*mColumnCount+index.column()))
//        {
//            return mQuery->value(0);
//        }
//        else
//        {
//            return QVariant();
//        }
//    }
//    if(role==ROLE_PERMISION)
//    {
//        if(mQuery->seek(index.row()*mColumnCount+index.column()))
//        {
//            return mQuery->value(1);
//        }
//        else
//        {
//            return QVariant();
//        }
//    }
    if(mQuery->seek(index.row()*mColumnCount+index.column()))
    {
        return mQuery->value(role-Qt::UserRole);
    }
    else
    {
        return QVariant();
    }
    return QVariant();
}

int UserModel::checkPasswd(const QString &name, const QString &passwd)
{
    DataBaseQuery query;
    query.selectTable(DBTabUser::TAB_NAME,NULL,DBTabUser::_USER_NAME +QString("=\"") + name + "\" and " + DBTabUser::_PASSWD + "=\"" + passwd + "\"");
    if(query.first())
    {
        QSqlRecord record = query.record();
        return record.value(record.indexOf(DBTabUser::_PERMISSION)).toInt();
    }
    return -1;
}
